package com.xjd.io.in;

import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * <pre>
 * <b>最大可读取InputStream</b>
 * 最多可读取maxRead大小的字节数
 *   如果当前InputStream能读取的字节数小于maxRead则读取所有字节
 *   如果当前InputStream能读取的字节数大于maxRead则读取maxRead大小的字节
 * </pre>
 * @author  elvis.xu
 * @version 2013-1-9 上午11:46:42
 */
public class MaxReadInputStream extends FilterInputStream {
	private long maxRead;
	private long remain;

	public long getMaxRead() {
		return maxRead;
	}
	
	public long getCurrentRead() {
		return maxRead - remain;
	}

	public MaxReadInputStream(InputStream in, long maxRead) {
		super(in);
		this.maxRead = maxRead;
		this.remain = maxRead;
	}

	@Override
	public int read() throws IOException {
		if (remain <= 0) {
			return -1;
		}
		int i = super.read();
		if (i != -1) {
			remain--;
		}
		return i;
	}

	@Override
	public int read(byte[] b) throws IOException {
		return read(b, 0, b.length);
	}

	@Override
	public int read(byte[] b, int off, int len) throws IOException {
		if (remain <= 0) {
			return -1;
		}
		int maxRead = (remain < len) ? (int) remain : len;
		int read = super.read(b, off, maxRead);
		if (read != -1) {
			remain -= read;
		}
		return read;
	}

	@Override
	public long skip(long n) throws IOException {
		if (remain <= 0) {
			return 0;
		}
		long maxSkip = (remain < n) ? remain : n;
		long skip = super.skip(maxSkip);
		remain -= skip;
		return skip;
	}
}
